from flask import Blueprint, render_template, jsonify, request
from models.entity.facility_type import FacilityType
from models.entity.facility import Facility
from models.entity.district_with_facility import DistrictWithFacility
from models.entity.district import District
import json
from utils.result import result

"""
这个文件完成的是对模块的管理，实现对模块的添加，删除和修改,查看
"""
mod = Blueprint("core_facility", __name__, url_prefix="/core/facility", template_folder="templates",
                static_folder="static")


@mod.route('/get_all_by_facility_type_id/', methods=['POST'])
def get_facility_by_type_id():
    """得到某个设施类型下的所有设施"""
    """
    {
        "id": 2
    }
    """
    try:
        dict = json.loads(request.data.decode("utf-8"))
    except:
        return result(success=0, error_code=-1, error_msg="json格式错误")
    id = dict['id']
    facilities = Facility.get_facilities_by_facility_type_id(id)
    t_list = [item.to_dict() for item in facilities]
    return result(success=1, data=t_list)


@mod.route('/get_all_by_district_id/',methods=["POST"])
def get_facility_by_district_id():
    """
    根据分区id获取设施
    """
    # request: json
    # {
    #       "id":id    // 分区id
    # }
    try:
        data = json.loads(request.data.decode("utf-8"))
    except:
        return result(success=0, error_code=-1, error_msg="json格式错误")
    all_facility = Facility.get_facilities_by_district_id(data["id"])
    t_list = [item.to_dict() for item in all_facility]
    return result(success=1, data=t_list)


@mod.route('/del/', methods=['GET', 'POST'])
def del_facility():
    """删除设施"""
    """
    {
    "id":2
    }
    """
    try:
        data = json.loads(request.data.decode("utf-8"))
        print('data', data)
    except:
        return result(success=0, error_code=-1, error_msg="json格式错误")
    id = data['id']
    print('id', id)
    if not Facility.get_facility_by_id(id):
        return result(success=0, error_code=-2, error_msg="没有这个设施")
    facility = Facility.get_facility_by_id(id)
    # 删除分区和设施的中间表信息
    connectors = DistrictWithFacility.query.filter_by(facility_id=id).all()
    print('connectors111111', connectors)
    for item in connectors:
        print('item', item)
        if item.delete() is False:
            return result(success=0, error_code=-2, error_msg="未知错误")
    # 删除设施信息
    if facility.delete():
        return result(success=1)
    else:
        return result(success=0, error_code=-2, error_msg="未知错误")


@mod.route('/add/', methods=['GET', 'POST'])
def add_facility():
    """
    {
    "name":"kddd12dk",
    "facility_type":1,
    "code":"dddhttd",
    "description":"fff",
    "status":1,
    "dis_order":3
    "district_id":1
    }
    """
    try:
        dict = json.loads(request.data.decode("utf-8"))
        print('dict', dict)
    except:
        return result(success=0, error_code=-1, error_msg="json格式错误")
    if "facility_type" not in dict:
        return result(success=0, error_code=-1, error_msg="没有选择设施或建筑物类型")
    facility_type = dict['facility_type']
    if not FacilityType.get_facility_type_by_id(facility_type):
        return result(success=0, error_code=-1, error_msg="设施或建筑物类型存在异常")

    # if not FacilityType.get_facility_type_by_name(dict.get('name')):
    #     return result(success=0, error_code=-1, error_msg="设施或建筑物类型存在异常")
    if "name" not in dict:
        return result(success=0, error_code=-1, error_msg="名称不能为空")
    if "code" not in dict:
        return result(success=0, error_code=-1, error_msg="编码不能为空")
    if "id" in dict:
        dict.pop("id")
    if Facility.get_facility_by_name(dict["name"]):
        return result(success=0, error_code=-2, error_msg="名称已经存在，重新填写")
    if Facility.get_facility_by_code(dict["code"]):
        return result(success=0, error_code=-6, error_msg="编码已经存在,重新填写")
    facility = Facility()
    try:
        facility.from_dict(dict)
    except RuntimeError as e:
        return result(success=0, error_code=-2, error_msg=str(e))
    if facility.save():
        connector=DistrictWithFacility()
        connector.facility_id=facility.id
        connector.district_id=dict["district_id"]
        if connector.save() is False:
            return result(success=0, error_code=-2, error_msg="未知错误")
        return result(success=1)
    else:
        return result(success=0, error_code=-2, error_msg="未知错误")


@mod.route('/edit/', methods=['GET', 'POST'])
def edit_facility():
    """这个函数的主要功能是编辑设施"""
    """
    {
    "id":1,
    "facility_type":4,
    "name":"3ere3",
    "code":"rrrff",
    "description":"ccccc",
    "dis_order":1,
    "status":3
    "district_id":1
    }
    """
    try:
        data = json.loads(request.data.decode("utf-8"))
    except:
        return result(success=0, error_code=-1, error_msg="json格式错误")
    print('data',data)
    print(111,type(data["facility_type"]))
    # if FacilityType().get_facility_type_by_id(data["facility_type"]) is None:
    #     return result(success=0, error_code=-1, error_msg="设备类型不存在，请重新填写")
    #     # return result(success=0, error_code=-1, error_msg="设备类型存在，ok")
    if not FacilityType.get_facility_type_by_id(data["facility_type"]):
        return result(success=0, error_code=-1, error_msg="设备类型不存在，请重新填写")
    facility = Facility.get_facility_by_id(data['id'])
    if not facility:
        return result(success=0, error_code=-1, error_msg="指定设施")
    if data["name"] != facility.name and Facility.get_facility_by_name(data["name"]) is not None:
        return result(success=0, error_code=-2, error_msg="设施名称已被占用")
    if data["code"] != facility.code and Facility.get_facility_by_code(data["code"]) is not None:
        return result(success=0, error_code=-9, error_msg="设施编码已被占用")

    ####我加的代码 .处理Facility模型没有district_id,所以用到第三张表 ,然而并没有用
    # connector = DistrictWithFacility.query.filter_by(facility_id=data['id']).first()
    # if connector is not None:
    #     data["district_id"] = connector.district_id
    # else:
    #     data["district_id"] = None
    # return data

    try:
        # facility.from_dict(data)
        facility.from_dict(data)
    except RuntimeError as e:
        return result(success=0, error_code=-2, error_msg=str(e))
    if facility.save():
        # 处理分区与设施的关系
        # 删除旧的关系
        old_connector=DistrictWithFacility.query.filter_by(facility_id=facility.id).first()
        if not old_connector is None:
            if old_connector.delete() is False:
                return result(success=0, error_code=-3, error_msg="未知错误")
        # 新建关系
        connector=DistrictWithFacility()
        connector.facility_id=facility.id
        connector.district_id=data["district_id"]
        if connector.save() is False:
            return result(success=0, error_code=-3, error_msg="未知错误")
        return result(success=1)
    else:
        return result(success=0, error_code=-3, error_msg="未知错误")


@mod.route('/get_all/', methods=['GET', 'POST'])
def get_facility_all():
    """得到所有的设施"""
    facilities = Facility().get_list_all()
    t_list = [item.to_dict() for item in facilities]
    return result(success=1, data=t_list)


@mod.route("/get_district_facility_tree/",methods=["POST"])
def get_district_and_facility_tree():
    """
    得到分区与设施的树
    请求参数: 无
    """
    def travel_tree(source):
        # 将分区与设施放在一棵树下
        def in_travel_tree(id_num):
            sz=[]
            for obj in source:
                if isinstance(obj,District):
                    if obj.parent_id==id_num:
                        dic=obj.to_dict()
                        facilities=District.get_facilities_by_district_id(obj.id)
                        if (len(District().get_list_by_pid(obj.id)) == 0) and (len(facilities) != 0):
                            # 如果该分区没有子分区并且本身具有设施
                            dic["children"] = []
                            for item in facilities:
                                dic["children"].append(item.to_dict())
                        else:
                            dic["children"] = in_travel_tree(obj.id)
                        sz.append(dic)
            return sz
        rlist=in_travel_tree(0)
        return rlist
    districts = District.get_first_level_districts()
    sources = []
    for item in districts:
        all_children = District.query.filter(District.path.like("%,"+str(item.id)+",%")).all()
        sources.append(all_children)
    t_list = [travel_tree(item)[0] for item in sources]
    return result(success=1, data=t_list)


@mod.route("/search/",methods=["POST"])
def search_facility():
    """
    模糊查询
    """
    # request: json
    # {
    #      "query_word": "lishimin"
    # }
    receive = request.data
    data = json.loads(receive.decode("utf-8"))
    tmp ={}
    extra =[]
    if 'query_word' in data:
        query_word = data['query_word']
    else:
        tmp['success'] = 0
        tmp['error_code'] = -9
        tmp['error_msg'] = "数据格式错误"
        tmp['data'] = extra
        return jsonify(tmp)
    facilities = Facility.search(query_word)
    return jsonify(facilities)